package com.lagou.myrpcconsumer.processor;

import com.lagou.myrpc.api.common.RpcResponse;
import com.lagou.myrpcconsumer.anno.RpcReference;
import com.lagou.myrpcconsumer.proxy.RpcClientProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Autowired
    private RpcClientProxy rpcClientProxy;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();
        for (Field field : beanClass.getDeclaredFields()) {
            if (field.getAnnotation(RpcReference.class) == null) {
                continue;
            }

            Object proxy = rpcClientProxy.createProxy(field.getType());
            try {
                field.setAccessible(true);
                field.set(bean, proxy);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return bean;
    }
}
